package com.ruoyi.test.serv.impl;

import com.ruoyi.test.dao.MessageDao;
import com.ruoyi.test.domain.Message;
import com.ruoyi.test.serv.IMessageServ;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

@Service
@Transactional
public class MessageServImpl implements IMessageServ {
    @Resource
    private MessageDao dao;

    @Override
    public void add(Message dto) {
        if (dto.getToChannelName() == null || dto.getToChannelName().isEmpty()) { // 如果不是频道里
            // 创建消息实体并保存
            Message msg = new Message();
            msg.setSenderId(dto.getSenderId());
            msg.setReceiverId(dto.getReceiverId());
            msg.setContent(dto.getContent());
            msg.setTimestamp(LocalDateTime.now());
            dao.add(msg);
        } else {
            // 创建消息实体并保存
            Message msg = new Message();
            msg.setSenderId(dto.getSenderId());
            msg.setReceiverId(dto.getReceiverId());
            msg.setToChannelName(dto.getToChannelName());
            msg.setContent(dto.getContent());
            msg.setTimestamp(LocalDateTime.now());
            dao.addToChatMessage(msg);

            dao.addToChatChannelMessage(msg);
        }

    }

    @Override
    public List<Message> selectAll(String senderId, String receiverId, String toChannelName) {
        if (toChannelName == null || toChannelName.isEmpty()) { // 如果不在频道中
            // 使用 isEmpty() 来检查 receiverId 是否为空字符串
            if (receiverId != null && receiverId.isEmpty()) {
                return dao.selectAll(senderId, "");
            }
            return dao.selectAll(senderId, receiverId);
        } else {
            return dao.selectAllForChannel(toChannelName);
        }

    }
}
